<template>
  <div class="update-avatar">
    <img :src="photo" alt="" ref="image" />

    <div class="toolbar">
      <span @click="$emit('close')">取消</span>
      <span @click="onConfirm">完成</span>
    </div>
  </div>
</template>
  
  <script>
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.css";
import { uploadPhoto } from '@/api';

export default {

  props: {
    photo: {
      type: String,
      required: true,
    },
  },

  data() {
    return {
      myCropper: null,
    };
  },

  mounted() {
    this.init()
  },

  methods: {
    init() {
      this.myCropper = new Cropper(this.$refs.image, {
        viewMode: 1,
        dragMode: "none",
        initialAspectRatio: 1,
        aspectRatio: 1,
        preview: ".before",
        background: false,
        autoCropArea: 0.6,
        zoomOnWheel: false,
      });
    },
    async onConfirm() {
      //获取裁剪后的canvas
      const canvas = this.myCropper.getCroppedCanvas()
      // console.log(canvas);
          //2 将canvas 转文件对象
      const file = await new Promise((resolve) => {
        canvas.toBlob((file) => {
           resolve(file)
        })
      })
      //  console.log(file)
      //3传服务端
      try {
        this.$toast.loading({
          message: '上传图片中',
          forbidClick: true
        })

        const { data } = await uploadPhoto(file)

        console.log(data);
        this.$toast.success('上传图片成功')
        
        // const { data } = await uploadPhoto(file)

        // // console.log(data);
        // this.$emit('update-photo' ,data.data.photo)
        // this.$toast.success('上传图片成功')

        this.$emit('close')
        
      } catch (err) {
         this.$toast.fail('上传图片失败')
      }
    }
  },
}
</script>
  
  <style scoped lang="less">
.update-avatar {
  background: #000;
  width: 100%;
  height: 100%;
  img {
    width: 100%;
    height: 65%;
    position: absolute;
    top: 50%;
    left: 0;
    transform: translateY(-50%);
    z-index: 9999;
  }
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 15px;
    box-sizing: border-box;
  }
}
</style>